<template>
  <view class="viewport">
    <scroll-view scroll-y>
      <view class="logo">
        <image src="/static/images/logo.png"></image>
      </view>
      <view class="login">
        <template>
          <uni-forms
            :model="registerForm"
            ref="registerFormRef"
            :rules="registerFormRules"
          >
            <uni-forms-item name="username">
              <uni-easyinput
                type="number"
                v-model="registerForm.username"
                placeholder="请输入账号"
              ></uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="password">
              <uni-easyinput
                type="password"
                v-model="registerForm.password"
                placeholder="请输入长度为8-16位字符字母/数字以及标点符号的密码"
              >
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="resetPassword">
              <uni-easyinput
                type="password"
                v-model="registerForm.resetPassword"
                placeholder="请输入重复密码"
              >
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="email">
              <uni-easyinput
                type="text"
                v-model="registerForm.email"
                placeholder="请输入绑定的邮箱"
              >
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="code">
              <uni-easyinput
                v-model="registerForm.code"
                placeholder="请输入4位验证码"
              >
                <template #right>
                  <button
                    class="code-btn"
                    :disabled="countdown > 0"
                    @tap="getEmailCaptcha()"
                  >
                    {{ countdown > 0 ? countdown + "秒后重发" : "获取验证码" }}
                  </button>
                </template>
              </uni-easyinput>
            </uni-forms-item>
            <button @tap="onSubmit" class="button phone">注册并登录</button>
          </uni-forms>
        </template>
      </view>
      <view class="tips" :class="{ animate__shakeY: isAgreePrivacyShakeY }">
        <label class="label" @tap="isAgreePrivacy = !isAgreePrivacy">
          <radio class="radio" color="#28bb9c" :checked="isAgreePrivacy" />
          <text>登录/注册即视为你同意校园投票</text>
        </label>
        <navigator class="link" hover-class="none" url="./protocal"
          >《服务条款》</navigator
        >
        和<text class="link" @tap="onOpenPrivacyContract">《隐私协议》</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { postLoginAPI, getEmailCodeAPI, userRegisterAPI } from "@/api/login";
import { useUserStore } from "@/stores";
import { userRegisterType } from "@/types/login";
import { reactive, ref } from "vue";

const userStore = useUserStore();

const registerForm: userRegisterType = reactive({
  username: "",
  password: "",
  resetPassword: "",
  email: "",
  code: "",
});

const registerFormRef = ref<UniHelper.UniFormsInstance>();

const registerFormRules: UniHelper.UniFormsRules = {
  username: {
    rules: [
      { required: true, errorMessage: "请输入账号" },
      {
        pattern: /^[a-zA-Z0-9]{3,10}$/,
        errorMessage: "请输入长度位3-10位的字母/数字账号",
      },
    ],
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: "请输入密码",
      },
      {
        pattern:
          /^(?=.*[a-zA-Z])(?=.*\d|.*[!@#$%^&*()_+\-=$${};':"\\|,.<>\/?]).{8,16}$/,
        errorMessage: "密码长度为8-16位，且包含字母和数字或特殊字符",
      },
    ],
  },
  resetPassword: {
    rules: [
      {
        required: true,
        errorMessage: "请输入重复密码",
      },
      {
        validateFunction: (rule, value, data, callback) => {
          if (value !== registerForm.password) {
            callback("两次密码输入不一致");
          }
          return true;
        },
      },
    ],
  },
  email: {
    rules: [
      { required: true, errorMessage: "请输入绑定的邮箱" },
      {
        pattern:
          /^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
        errorMessage: "请输入正确格式的邮箱",
      },
    ],
  },
  code: {
    rules: [
      {
        required: true,
        errorMessage: "请输入验证码",
      },
      {
        validateFunction: function (rule, value, data, callback) {
          if (value.length !== 4) {
            callback("验证码为4位");
          }
          return true;
        },
      },
    ],
  },
};

// 表单提交
const onSubmit = async () => {
  await checkedAgreePrivacy();
  await registerFormRef.value?.validate?.();
  await userRegisterAPI(registerForm);
  const res = await postLoginAPI({
    username: registerForm.username,
    password: registerForm.password,
  });
  userStore.token = res.data;
  userStore.username = registerForm.username;
  await userStore.setUserInfo();
  uni.switchTab({ url: "/pages/my/my" });
};

// 请先阅读并勾选协议
const isAgreePrivacy = ref(false);
const isAgreePrivacyShakeY = ref(false);
const checkedAgreePrivacy = async () => {
  if (!isAgreePrivacy.value) {
    uni.showToast({
      icon: "none",
      title: "请先阅读并勾选协议",
    });
    // 震动提示
    isAgreePrivacyShakeY.value = true;
    setTimeout(() => {
      isAgreePrivacyShakeY.value = false;
    }, 500);
    // 返回错误
    return Promise.reject(new Error("请先阅读并勾选协议"));
  }
};

const onOpenPrivacyContract = () => {
  // #ifdef MP-WEIXIN
  // 跳转至隐私协议页面
  wx.openPrivacyContract({});
  // #endif
};

let countdown = ref(0);

const setTimer = () => {
  // 设置60秒的倒计时
  countdown.value = 60;
  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};

// 获取邮箱验证码
const getEmailCaptcha = async () => {
  await registerFormRef.value?.validateField?.("email");
  setTimer();
  await getEmailCodeAPI({
    email: registerForm.email,
    type: "register",
  });
  uni.showToast({
    icon: "none",
    title: "验证码已发送，请注意查收",
  });
};
</script>

<style lang="scss">
:deep(.uni-easyinput__content-input) {
  height: 78rpx !important;
}
.viewport {
  display: flex;
  flex-direction: column;
  padding: 20rpx 40rpx;
}

.login {
  height: 58vh;
  padding: 40rpx 20rpx 20rpx;

  .login-header {
    display: flex;
    justify-content: space-around;
    margin: 20rpx 0 30rpx;
    .login-title {
      font-size: 32rpx;
      color: #333;
    }
    .active {
      font-weight: bold;
      ::after {
        content: "";
        display: block;
        height: 2px;
        width: 80%;
        margin: 0 auto;
        background-color: #28bb9c;
        margin-top: 10rpx;
      }
    }
  }

  .input-margin {
    margin-top: 20rpx;
  }

  .code-btn {
    line-height: 78rpx;
    font-size: 28rpx;
    color: #333;
  }

  .button-extra {
    display: flex;
    justify-content: space-between;
    margin: 14rpx 2rpx 20rpx;
    .caption {
      font-size: 24rpx;
      color: #28bb9c;
    }
  }

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 8rpx;
    color: #fff;
    .icon {
      font-size: 40rpx;
      margin-right: 6rpx;
    }
  }

  .phone {
    background-color: #28bb9c;
  }

  .wechat {
    background-color: #06c05f;
  }

  .extra {
    flex: 1;
    padding: 70rpx 70rpx 0;
    .caption {
      width: 440rpx;
      line-height: 1;
      border-top: 1rpx solid #ddd;
      font-size: 26rpx;
      color: #999;
      position: relative;
      text {
        transform: translate(-40%);
        background-color: #fff;
        position: absolute;
        top: -12rpx;
        left: 50%;
      }
    }

    .options {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 70rpx;
      button {
        padding: 0;
        background-color: transparent;
        &::after {
          border: none;
        }
      }
    }

    .icon {
      font-size: 24rpx;
      color: #444;
      display: flex;
      flex-direction: column;
      align-items: center;

      &::before {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 6rpx;
        font-size: 40rpx;
        border: 1rpx solid #444;
        border-radius: 50%;
      }
    }
    .icon-weixin::before {
      border-color: #06c05f;
      color: #06c05f;
    }
  }
}

.logo {
  flex: 1;
  text-align: center;
  image {
    width: 220rpx;
    height: 220rpx;
    margin-top: 10vh;
  }
}

@keyframes animate__shakeY {
  0% {
    transform: translate(0, 0);
  }
  50% {
    transform: translate(0, -5rpx);
  }
  100% {
    transform: translate(0, 0);
  }
}

.animate__shakeY {
  animation: animate__shakeY 0.2s ease-in-out 3;
}

.button-privacy-wrap {
  position: relative;
}

.tips {
  padding: 40rpx 0;
  font-size: 22rpx;
  color: #999;
  text-align: center;

  .radio {
    transform: scale(0.6);
    margin-right: -4rpx;
    margin-top: -4rpx;
    vertical-align: middle;
  }

  .link {
    display: inline;
    color: #28bb9c;
  }
}
</style>
